package com.chuangke.file.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import com.chuangke.common.exception.ChuangkeException;

import net.coobird.thumbnailator.Thumbnails;

public class ImageUtils {

	public static byte[] createThumbnailByPdf(byte[] pdfBytes) {
		byte[] outbyte = null;
		try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
			PDDocument doc = PDDocument.load(pdfBytes);
			PDFRenderer renderer = new PDFRenderer(doc);
			BufferedImage image = renderer.renderImage(0, 1.9f);
			ImageIO.write(image, "JPEG", output);
			outbyte = output.toByteArray();
			doc.close();
		} catch (Exception e) {
			throw new ChuangkeException(e);
		}
		return createThumbnailByImage(outbyte);
	}

	public static byte[] createThumbnailByImage(byte[] imageBytes) {
		byte[] outbyte = null;
		try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
			Thumbnails.of(new BufferedInputStream(new ByteArrayInputStream(imageBytes))).size(167, 224)
					.outputFormat("jpg").outputQuality(0.5f).toOutputStream(output);
			outbyte = output.toByteArray();
		} catch (IOException e) {
			throw new ChuangkeException(e);
		}
		return outbyte;
	}
}
